<template>
  <div>
    <div
      class="w-[350px] border border-gray-200 bg-white p-3 shadow-md rounded-lg"
      @click="openDrawer"
    >
      <Handle type="target" :position="Position.Left" />
      <div class="flex flex-col gap-y-1">
        <common-title-module />
        <CommonDisplayModule title="输入" value-name="vartype" :valueList="data?.inoutlist" />
        <CommonDisplayModule title="输出" value-name="vartype" :valueList="data?.commonoutvo" />
      </div>
      <Handle type="source" :position="Position.Right" />
    </div>
    <RetrievalDrawerModule
      ref="drawerRef"
      :title="node?.node?.label"
      desc="在选定的知识中,根据输入变量召回最匹配的信息,并以列表形式返回"
      :form="data"
      @add="handleClickAddBtn"
      @remove="handleClickDeleteBtn"
      @cancel="onCancel"
    />
  </div>
</template>
<script setup>
import { ref } from 'vue'
import { Handle, Position, useNode, useVueFlow } from '@vue-flow/core'

import { editNode } from '@/api/modules/flow'

import CommonTitleModule from '../modules/common-title-module.vue'
import CommonDisplayModule from '../modules/common-display-module.vue'
import RetrievalDrawerModule from '../modules/retrieval-drawer-module.vue'

const node = useNode()

const data = ref({
  knowledgeid: node.node.data.knowledgeid ? node.node.data.knowledgeid.split(',') : [],
  segmentmaxilength: node.node.data.segmentmaxilength || 5,
  minmatch: node.node.data.minmatch || 0.5,
  segmenttag: node.node.data.segmenttag || 'dd6c1426bc2644e796dea54946c38a6f',
  isselect: !!node.node.data.isselect,
  isresult: !!node.node.data.isresult,
  isonlydoc: !!node.node.data.isonlydoc,
  inoutlist: node.node.data.inoutlist || [
    {
      varname: 'Query',
      varparam: '',
      vartype: 'String'
    }
  ],
  commonoutvo: [
    {
      varname: 'outputList',
      vartype: 'Array<Object>',
      children: [
        {
          varname: 'output',
          vartype: 'String'
        }
      ]
    }
  ]
})

const drawerRef = ref(null)
const openDrawer = () => {
  drawerRef.value?.init()
}

function handleClickAddBtn(listKey) {
  data.value[listKey].push({
    varname: '',
    varparam: '',
    vartype: 'String'
  })
  node.node.data = {
    ...node.node.data,
    output: data
  }
}

function handleClickDeleteBtn(listKey, index) {
  data.value[listKey].splice(index, 1)
  node.node.data = {
    ...node.node.data,
    output: data
  }
}

const onCancel = () => {
  const knowledgename = drawerRef.value.knowledgeList.map(item=>item.name)
  editNode({
    data: {
      id: node.id,
      ...data.value,
      knowledgeid: data.value.knowledgeid.toString(),
      knowledgename: knowledgename.toString(),
      commonoutvo: data.value.commonoutvo.reduce((pre, cur) => {
        pre[cur.varname] = cur.vartype
        return pre
      }, {})
    }
  })
}
</script>
